<template>
  <div class="field-variable">
    <div class="field-search">
      <el-input
        v-model="searchVal"
        placeholder="搜索变量"
        prefix-icon="el-icon-search"
        clearable
        @change="search"
      />
    </div>
    <div style="max-height: 400px; overflow-y: auto;">
      <el-tree
        :data="dataList"
        :props="defaultProps"
        :default-expanded-keys="extendKeys"
        node-key="enCode"
        highlight-current
        @current-change="fieldChiose"
      />
    </div>
  </div>
</template>

<script>
export default {
  components: {},
  props: {
    fieldList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      type: {
        string: {
          text: '字符串',
          type: null
        },
        number: {
          text: '数字',
          type: 'success'
        },
        array: {
          text: '数组',
          type: 'warning'
        },
        datetime: {
          text: '时间',
          type: 'info'
        }
      },
      searchVal: null,
      defaultProps: {
        children: 'children',
        label: 'label',
        disabled: (item, node) => {
          return item.disabled
        }
      },
      extendKeys: [],
      dataList: []
    }
  },
  computed: {},
  watch: {
    fieldList: {
      handler(val) {
        this.reset()
      },
      immediate: true
    }
  },
  mounted() {},
  methods: {
    chioseField(item) {
      this.$emit('chiose', item)
    },
    reset() {
      this.extendKeys = []
      if (this.fieldList && this.fieldList.length > 0) {
        this.loadExtends(this.fieldList)
      }
      this.dataList = this.fieldList
    },
    loadExtends(list) {
      list.forEach(c => {
        if (c.children && c.children.length > 0) {
          this.extendKeys.push(c.enCode)
          this.loadExtends(c.children)
        }
      })
    },
    fieldChiose(e) {
      if (e.disabled) {
        return
      }
      this.$emit('chiose', e)
    },
    search() {
      if (this.searchVal == null || this.searchVal === '') {
        this.dataList = this.fieldList
      } else {
        this.dataList = this.fieldList.filter((c) =>
          c.includes(this.searchVal)
        )
      }
    }
  }
}
</script>
<style scoped>
.field-variable {
   width: 100%;
    padding: 10px;
    overflow-y: auto;
    height: 100%;
    display: inline-block;
}
.field-variable .field-search {
  margin-bottom: 10px;
}
.field-variable .field-item {
  cursor: pointer;
  padding: 5px;
  line-height: 40px;
  height: 40px;
  text-align: left;
  position: relative;
}
.field-variable .title {
    position: absolute;
    top: -1px;
}
.dark .field-variable .field-item:hover {
  background-color: #1d1e1f !important
}

.field-variable .el-tag {
   float: right;
}
</style>
